package iplocation

import (
	"fmt"
	"net"
	"strings"

	"github.com/oschwald/geoip2-golang"
)

type IPDB struct {
	DBFile string
	Reader *geoip2.Reader
}

func(db *IPDB) Init() error {
	var err error
	db.Reader, err = geoip2.Open(db.DBFile)
	return err
}

func(db *IPDB) Close() {
	db.Reader.Close()
}
func(db *IPDB) Location(addr string) (float64,float64,error){
	addrIp := strings.Split(addr,":")
	ipstr := string(addrIp[0])
	ip := net.ParseIP(ipstr)
	if ip == nil {
		return 0.,0.,fmt.Errorf("Parse Ip failure")
	}
	record, err := db.Reader.City(ip)
	if err != nil {
		return 0.,0.,fmt.Errorf("locate %s failure, %v",addr,err)
	}
	return record.Location.Longitude, record.Location.Latitude, err
}